'use strict'

$(function(){
  var studentToken = getCookie('enjoy_shadow_student_token')
  var awardAmount = 0.88
  var _id = $('meta[name=shareId]').attr('content')
  var phoneNumber;

  var articleQuestion = $('#articleQuestion').text().split('\n');
  var aqHTML = ''
  for(var aq in articleQuestion){
    if(articleQuestion[aq] && articleQuestion.hasOwnProperty(aq)){
    aqHTML += '<p>'+articleQuestion[aq]+'</p>'
    }else{
      aqHTML += '<p class="blankLine"> </p>'
    }
  }
  $('#articleQuestion').html(aqHTML)

  var userShow=false

  $('.user').click(function(){
    if(!userShow){
    $('.userPanel').show().animate({top:'1.8rem',opacity:1})
      userShow=true
    }else{
      $('.userPanel').animate({top:'-3rem',opacity:0},function(){
        $(this).hide()
      })
      userShow=false
    }
    return false
  })
  $('body').click(function(){
    $('.userPanel').animate({top:'-3rem',opacity:0},function(){
      $(this).hide()
    })
    userShow=false
  })

  $('#submit').click(submitFunction)


  var submitFunction = function(){
    $('.learningScholar').text(awardAmount)
    var ans1 = $('.answer1.chosen').data('ans')
    var ans2 = $('.answer2.chosen').data('ans')
    var right1 = $('#q1right').val()
    var right2 = $('#q2right').val()
    if(!ans1 || !ans2){
      alert('没有选择答案，无法提交')
      return
    }

    if(ans1===right1 || ans2===right2){

      $.ajax('/student/answerRight',{
        method:'POST',
        type:'json',
        data:{
          token:studentToken,
          _id:_id
        },
        success:function(d){
          if(d && d.success){
            console.log('获得奖励金')
            $('.pack-wrapper').show()
          }else{
            console.error('发生错误，未领到')
          }
        }
      })

    }else{
      $('.wrong-wrapper').show()
    }
  }


  if(studentToken){
    $.ajax('/student/autoLogin',{
      method:'POST',
      type:'json',
      data:{
        token:studentToken,
        _id:_id
      },
      success:function(d){
        if(!d.success){
          delCookie('enjoy_shadow_student_token')
          console.log('非法进入，退出中...');
          $('.login-wrapper').show()
          return
        }
        if(d.article){
          $('#articleContent').val(d.article)
        }else{
          $('#articleContent').val('')
        }

        if(d.recentLesson.title){
          $('#userLesson').prop('href','/homework/'+d.recentLesson._id)
          $('#lessonTitle').html('<span>'+d.recentLesson.title+'</span>')
        }else{
          $('#userLesson').prop('src','javascript:;')
          $('#lessonTitle').text('您还未学习任何课程')
        }
        $('#totalAward').text(d.totalAward.toFixed(2))
        phoneNumber = d.phone
        awardAmount = d.award
        $('.learningScholar').text(awardAmount)
        var myAward = new CountUp('scholar', 0, d.award, 2, 4, options);
        if (!myAward.error) {
          myAward.start();
        } else {
          console.error(myAward.error);
        }
        $('.login-wrapper').hide()
        if(!d.alreadyGotTodayPack){
          $('.scholarTip').animate({opacity:1,left:'1rem'},2000)
          $('.alreadyTip').animate({opacity:0,left:'1rem'},2000)
          $('#submit').css('backgroundColor','#ffb515').bind('click',submitFunction)
        }else{
          $('.alreadyTip').animate({opacity:1,left:'1rem'},2000)
          $('.scholarTip').animate({opacity:0,left:'1rem'},2000)
          $('#submit').css('backgroundColor','#ddd').unbind('click')
        }

        if(d.notGottenPack){
          $('.pack-wrapper').show()
          return
        }


      },
      error:function(d){
        $('.login-wrapper').show()
      }
    })
  }else{
    $('.login-wrapper').show()
  }


  $('.close-rect').click(function(){
    $('.success-wrapper').hide()
  })


  $('.answer1').click(function(){
    $('.answer1').not(this).removeClass('chosen')
    $(this).addClass('chosen')
  })

  $('.answer2').click(function(){
    $('.answer2').not(this).removeClass('chosen')
    $(this).addClass('chosen')
  })

  var options = {
    useEasing: true,
    useGrouping: true,
    separator: ',',
    decimal: '.',
  };
  var demo = new CountUp('scholar', 0, awardAmount, 2, 4, options);
  if (!demo.error) {
    demo.start();
  } else {
    console.error(demo.error);
  }

  $('#articleContent').on('input propertychange',function(){
    $('#textNum').text(' '+$('#articleContent').val().length)
  })


  $('.submitSave').click(function(){
    var articleContent = $('#articleContent').val()

    $.ajax('/student/sendArticle', {
      method: 'POST',
      type: 'json',
      data: {
        token: studentToken,
        _id: _id,
        article: articleContent
      },
      success: function (d) {
        if(d && d.success){
          alert('您的随笔已经提交给班主任，\r\n请随时关注群内评选！\r\n若有更新，可以在本页面重新编辑并提交。')
        }else{
          if(d.errMsg){
            alert('您输入的内容为空')
          }
          console.error(d.errMsg)
        }
      }
    })
      })

  $('#logout').click(function(){
    delCookie('enjoy_shadow_student_token')
    $('.login-wrapper').show()
  })


  $('#login').click(function(){
    var phone = $('#phone').val()
    if(!(/^1(3|4|5|7|8)\d{9}$/.test(phone))){
      alert("手机号码有误，请重填");
      return false;
    }
    $.ajax('/student/login',{
      method:'POST',
      type:'json',
      data:{
        phone:phone,
        _id:_id
      },
      success:function(d){
        if(d.notGottenPack){
          $('.pack-wrapper').show()
        }
        if(d.article){
          $('#articleContent').val(d.article)
        }else{
          $('#articleContent').val('')
        }

        if(d.recentLesson.title){
          $('#userLesson').prop('href','/homework/'+d.recentLesson._id)
          $('#lessonTitle').html('<span>'+d.recentLesson.title+'</span>')
        }else{
          $('#userLesson').prop('src','javascript:;')
          $('#lessonTitle').text('您还未学习任何课程')
        }
        $('#totalAward').text(d.totalAward.toFixed(2))
        awardAmount = d.award
        phoneNumber = phone
        $('.learningScholar').text(awardAmount)
        var myAward = new CountUp('scholar', 0, d.award, 2, 4, options);
        if (!myAward.error) {
          myAward.start();
        } else {
          console.error(myAward.error);
        }

        if(!d.alreadyGotTodayPack){
          $('.scholarTip').animate({opacity:1,left:'1rem'},2000)
          $('.alreadyTip').animate({opacity:0,left:'1rem'},2000)
          $('#submit').css('backgroundColor','#ffb515').bind('click',submitFunction)
        }else{
          $('.alreadyTip').animate({opacity:1,left:'1rem'},2000)
          $('.scholarTip').animate({opacity:0,left:'1rem'},2000)
          $('#submit').css('backgroundColor','#ddd').unbind('click')
        }

        $('.login-wrapper').hide()
        setCookie('enjoy_shadow_student_token',d.token)
        studentToken = d.token
      }
    })

  })



  $('#withdraw').click(function(){
    $.ajax('/student/withdraw',{
      method:'POST',
      type:'json',
      data:{
        token:studentToken,
        _id:_id
      },
      success:function(d){
        if(!d){
          console.error('网络通讯中断')
        }

        if(d.success){
          if(d.notRegistered){
          //  客户未注册
            $('.pack-wrapper').hide()
            $('.new-wrapper').show()
            return
          }
          if(d.alreadyGotten){
            $('.pack-wrapper').hide()
            $('.success-title p').text('你已经领取过本课的奖励金')
            $('.success-wrapper').show()
            return
          }

          if(d.sendCouponSuccess){
            $('.pack-wrapper').hide()
            $('.success-title p').text('成功领取学习奖励金！')
            $('.success-wrapper').show()
          }
        }else{
          if(d.errMsg===10009){
            $('.pack-wrapper').hide()
            $('.success-title p').text('今天已领过奖励金啦~')
            $('.success-wrapper').show()
            return
          }
        }
      }
    })
  })

  $('.register-page').click(function(){
    window.location = 'https://hd.rijin.com/ririjin/register/views/verify-code.html?cellphone='+phoneNumber
    // window.location = 'https://pm.rd.rijin.com/ririjin/share/0000002/views/verify-code.html?cellphone='+phoneNumber
  })
})
